/**
 * 对话内存 - IntelliMark适配版
 * 简化版本的对话记忆管理
 */

import { BaseMessage, HumanMessage, AIMessage, SystemMessage } from "@langchain/core/messages";
import { ConversationalMemory as IConversationalMemory } from "../types/memory";

export class ConversationalMemory implements IConversationalMemory {
  public type: 'conversational' = 'conversational';
  public namespace: string;
  public enabled: boolean;
  public messages: BaseMessage[];
  public maxMessages: number;
  public returnMessages: boolean;

  constructor(namespace: string = 'default', maxMessages: number = 20) {
    this.namespace = namespace;
    this.enabled = true;
    this.messages = [];
    this.maxMessages = maxMessages;
    this.returnMessages = true;
  }

  async addMessage(message: BaseMessage): Promise<void> {
    this.messages.push(message);

    // 保持消息数量在限制内
    if (this.messages.length > this.maxMessages) {
      this.messages = this.messages.slice(-this.maxMessages);
    }
  }

  getMessages(limit?: number): BaseMessage[] {
    if (limit) {
      return this.messages.slice(-limit);
    }
    return [...this.messages];
  }

  searchMessages(query: string, limit?: number): BaseMessage[] {
    const searchLower = query.toLowerCase();
    const filtered = this.messages.filter(msg =>
      msg.content.toLowerCase().includes(searchLower)
    );
    return limit ? filtered.slice(-limit) : filtered;
  }

  async deleteMessage(messageId: string): Promise<void> {
    // 简化实现：通过内容匹配删除
    this.messages = this.messages.filter(msg =>
      !(msg.content.includes(messageId))
    );
  }

  async clear(): Promise<void> {
    this.messages = [];
  }

  async save(): Promise<void> {
    // 简化实现：在内存中保存
    // 在实际应用中，这里应该保存到持久化存储
  }

  async load(): Promise<void> {
    // 简化实现：从内存中加载
    // 在实际应用中，这里应该从持久化存储加载
  }
}

export default ConversationalMemory;